package com.zjhn.ds.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjhn.ds.common.BizResult;
import com.zjhn.ds.common.PageBean;
import com.zjhn.ds.common.PageResult;
import com.zjhn.ds.domain.dto.pc.EquipmentTypeDto;
import com.zjhn.ds.domain.dto.pc.ModelDto;
import com.zjhn.ds.domain.entity.jlw.Equipment;
import com.zjhn.ds.domain.entity.jlw.EquipmentType;
import com.zjhn.ds.domain.entity.jlw.Model;
import com.zjhn.ds.domain.vo.ModelVo;
import com.zjhn.ds.mapper.EquipmentMapper;
import com.zjhn.ds.mapper.EquipmentTypeMapper;
import com.zjhn.ds.mapper.ModelMapper;
import com.zjhn.ds.param.AddUpdateModelParam;
import com.zjhn.ds.param.AddUpdateTypeParam;
import com.zjhn.ds.param.ModelPageParam;
import com.zjhn.ds.service.ModelTypeService;
import com.zjhn.ds.utils.CommonUtil;
import com.zjhn.ds.utils.base.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @BelongsProject: ds_jlw
 * @BelongsPackage: com.zjhn.ds.service.impl
 * @Author: sxt
 * @CreateTime: 2023-09-12  18:32
 * @Description:
 * @Version: 1.0
 */
@Service
public class ModelTypeServiceImpl implements ModelTypeService {

    @Resource
    private CommonUtil commonUtil;

    @Resource
    private EquipmentTypeMapper equipmentTypeMapper;

    @Resource
    private ModelMapper modelMapper;

    @Resource
    private EquipmentMapper equipmentMapper;

    /**
     * 新增/编辑设备类别
     *
     * @param param
     * @return
     */
    @Override
    public BizResult<?> addUpdateType(AddUpdateTypeParam param) {
        EquipmentType equipmentType;
        if (StringUtils.isNotBlank(param.getTypeId())) {
            // 更新
            equipmentType = equipmentTypeMapper.selectById(param.getTypeId());
            if (equipmentType == null)
                return BizResult.fail("设备类别不存在");

            EquipmentType another = equipmentTypeMapper.selectOne(new QueryWrapper<EquipmentType>()
                    .eq("type_name", param.getTypeName()).ne("id", param.getTypeId()));
            if (another != null)
                return BizResult.fail("设备类别已存在");

            equipmentType.setTypeName(param.getTypeName());
            equipmentTypeMapper.updateById(equipmentType);
        } else {
            // 新增
            equipmentType = equipmentTypeMapper
                    .selectOne(new QueryWrapper<EquipmentType>().eq("type_name", param.getTypeName()));
            if (equipmentType != null)
                return BizResult.fail("设备类别已存在");

            equipmentType = EquipmentType.builder().typeName(param.getTypeName()).build();
            equipmentTypeMapper.insert(equipmentType);
        }
        // redis 更新
        commonUtil.updateEquipmentType(equipmentType.getId(), equipmentType.getTypeName());

        return BizResult.success();
    }

    /**
     * 删除设备类别
     *
     * @param typeId
     * @return
     */
    @Override
    public BizResult<?> removeType(String typeId) {
        Integer count = equipmentMapper.selectCount(new QueryWrapper<Equipment>().eq("equipment_type_id", typeId));
        if (count > 0)
            return BizResult.fail("设备类别正在使用");

        equipmentTypeMapper.deleteById(typeId);
        // redis 更新
        commonUtil.removeEquipmentType(typeId);

        return BizResult.success();
    }

    /**
     * 分页查询设备类别
     *
     * @param param
     * @return
     */
    @Override
    public BizResult<PageResult<EquipmentTypeDto>> typePage(PageBean param) {
        IPage<EquipmentType> page = equipmentTypeMapper
                .selectPage(new Page<>(param.getCurrent(), param.getSize()), new QueryWrapper<EquipmentType>().orderByAsc("create_time"));

        IPage<EquipmentTypeDto> convert = page.convert(c ->
                EquipmentTypeDto.builder()
                        .typeId(c.getId())
                        .typeName(c.getTypeName())
                        .createTime(DateUtil.formatDateToString(c.getCreateTime()))
                        .build());

        return BizResult.success(PageResult.<EquipmentTypeDto>builder()
                .current(convert.getCurrent())
                .pages(convert.getPages())
                .size(convert.getSize())
                .total(convert.getTotal())
                .record(convert.getRecords())
                .build());
    }

    /**
     * 新增/编辑模型
     *
     * @param param
     * @return
     */
    @Override
    public BizResult<?> addUpdateModel(AddUpdateModelParam param) {
        Model model;
        if (StringUtils.isNotBlank(param.getModelId())) {
            // 更新
            model = modelMapper.selectById(param.getModelId());
            if (model == null)
                return BizResult.fail("模型不存在");

            Model another = modelMapper.selectOne(
                    new QueryWrapper<Model>()
                            .and(c -> c
                                    .eq("model_name", param.getModelName())
                                    .or()
                                    .eq("model_code", param.getModelCode()))
                            .ne("id", param.getModelId())
            );
            if (another != null)
                return BizResult.fail("模型名称编码已存在");
            model.setModelName(param.getModelName());
            model.setModelCode(param.getModelCode());
            model.setNeedleCode(param.getNeedleCode());
            model.setNeedleNumber(param.getNeedleNumber());
            model.setStockingsCode(param.getStockingsCode());
            modelMapper.updateById(model);
        } else {
            // 新增
            model = modelMapper.selectOne(
                    new QueryWrapper<Model>()
                            .eq("model_name", param.getModelName())
                            .or()
                            .eq("model_code", param.getModelCode()));
            if (model != null)
                return BizResult.fail("模型名称编码已存在");

            model = Model.builder()
                    .modelName(param.getModelName())
                    .modelCode(param.getModelCode())
                    .needleCode(param.getNeedleCode())
                    .needleNumber(param.getNeedleNumber())
                    .stockingsCode(param.getStockingsCode())
                    .build();
            modelMapper.insert(model);
        }
        // redis 更新
        commonUtil.updateModelInfo(model.getId(),
                ModelVo.builder()
                        .id(model.getId())
                        .modelName(param.getModelName())
                        .modelCode(param.getModelCode())
                        .needleCode(param.getNeedleCode())
                        .needleNumber(param.getNeedleNumber())
                        .stockingsCode(param.getStockingsCode())
                        .build());

        return BizResult.success();
    }

    /**
     * 删除模型
     * @param modelId
     * @return
     */
    @Override
    public BizResult<?> removeModel(String modelId) {
        Integer count = equipmentMapper.selectCount(new QueryWrapper<Equipment>().eq("model_id", modelId));
        if (count > 0)
            return BizResult.fail("模型已使用");

        modelMapper.deleteById(modelId);
        commonUtil.removeModelInfo(modelId);

        return BizResult.success();
    }

    /**
     * 按条件分页查询模型
     * @param param
     * @return
     */
    @Override
    public BizResult<PageResult<ModelDto>> modelPage(ModelPageParam param) {
        QueryWrapper<Model> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(param.getModelName()))
            queryWrapper.like("model_name", param.getModelName());
        if (StringUtils.isNotBlank(param.getModelCode()))
            queryWrapper.like("model_code", param.getModelCode());

        Page<Model> page = modelMapper.selectPage(
                new Page<>(param.getCurrent(), param.getSize()),
                queryWrapper.orderByAsc("create_time")
        );

        // 对象转化
        IPage<ModelDto> convert = page.convert(c ->
                ModelDto.builder()
                        .modelId(c.getId())
                        .modelName(c.getModelName())
                        .modelCode(c.getModelCode())
                        .needleCode(c.getNeedleCode())
                        .needleNumber(c.getNeedleNumber())
                        .stockingsCode(c.getStockingsCode())
                        .createTime(DateUtil.formatDateToString(c.getCreateTime()))
                        .build());

        return BizResult.success(PageResult.<ModelDto>builder()
                .current(convert.getCurrent())
                .pages(convert.getPages())
                .size(convert.getSize())
                .total(convert.getTotal())
                .record(convert.getRecords())
                .build());
    }


}
